import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class SqfliteHelper<T extends BaseModel> {
  static final Map<String, SqfliteHelper> _instances = {};
  static Database? _database;
// 这里可以定义数据库的名字和版本
  String tableName;

  SqfliteHelper._internal(this.tableName);

  // 工厂构造函数，根据 tableName 返回相应的实例
  factory SqfliteHelper(String tableName) {
    if (_instances.containsKey(tableName)) {
      return _instances[tableName] as SqfliteHelper<T>;
    } else {
      final instance = SqfliteHelper<T>._internal(tableName);
      _instances[tableName] = instance;
      return instance;
    }
  }
  Future<Database> get database async {
    if (_database != null) return _database!;

    ///创建数据库表
    _database = await _initDB();
    return _database!;
  }

  Future<Database> _initDB() async {
    String path = join(await getDatabasesPath(), 'app_database.db');
    return await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) {
        // 在此处初始化数据库并创建表
        // 使用 SQL 创建语句来定义主键
        db.execute('''
          CREATE TABLE $tableName (
            id INTEGER PRIMARY KEY AUTOINCREMENT, -- 定义 id 为主键，自动递增
            otherColumn TEXT
          )
        ''');
      },
    );
  }

  ///增

  Future<void> insert(T model) async {
    final db = await database;
    await db.insert(tableName, model.toMap());
  }

  Future<List<T>> getAll(
      {required T Function(Map<String, dynamic>) fromMap}) async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(tableName);
    return List.generate(maps.length, (i) {
      return fromMap(maps[i]);
    });
  }

  Future<void> update(T model, String idColumn, int id) async {
    final db = await database;
    await db.update(tableName, model.toMap(),
        where: '$idColumn = ?', whereArgs: [id]);
  }

  Future<void> delete(String idColumn, int id) async {
    final db = await database;
    await db.delete(tableName, where: '$idColumn = ?', whereArgs: [id]);
  }
}

abstract class BaseModel {
  Map<String, dynamic> toMap();
  BaseModel fromMap(Map<String, dynamic> map);

  ///子类例子
  //   @override
  // Map<String, dynamic> toMap() {
  //   return {
  //     'id': id,
  //     'name': name,
  //   };
  // }

  // @override
  // User fromMap(Map<String, dynamic> map) {
  //   return User(
  //     id: map['id'],
  //     name: map['name'],
  //   );
  // }
}

// ///使用例子
// void main() async {
//   final userHelper = DatabaseHelper<User>(tableName: 'users');
  
//   // 插入数据
//   await userHelper.insert(User(id: 1, name: 'John Doe'));

//   // 获取所有数据
//   List<User> users = await userHelper.getAll(fromMap: (map) => User().fromMap(map));
//   print(users);

//   // 更新数据
//   await userHelper.update(User(id: 1, name: 'Jane Doe'), 'id', 1);

//   // 删除数据
//   await userHelper.delete('id', 1);
// }

